package com.hulk.dryad.common.os;

import cn.hutool.core.date.DatePattern;
import com.hulk.dryad.common.util.Arith;
import lombok.EqualsAndHashCode;
import lombok.ToString;
import lombok.experimental.Accessors;

import java.lang.management.ManagementFactory;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;

/**
 * JVM相关信息
 *
 * @author hulk
 */
@ToString
@EqualsAndHashCode
@Accessors(chain = true)
public class Jvm {
  /** 当前JVM占用的内存总数(M) */
  private double total;

  /** JVM最大可用内存总数(M) */
  private double max;

  /** JVM空闲内存(M) */
  private double free;

  /** JDK版本 */
  private String version;

  /** JDK路径 */
  private String home;

  public double getTotal() {
    return Arith.div(total, (1024 * 1024), 2);
  }

  public void setTotal(double total) {
    this.total = total;
  }

  public double getMax() {
    return Arith.div(max, (1024 * 1024), 2);
  }

  public void setMax(double max) {
    this.max = max;
  }

  public double getFree() {
    return Arith.div(free, (1024 * 1024), 2);
  }

  public void setFree(double free) {
    this.free = free;
  }

  public double getUsed() {
    return Arith.div(total - free, (1024 * 1024), 2);
  }

  public double getUsage() {
    return Arith.mul(Arith.div(total - free, total, 4), 100);
  }

  /** 获取JDK名称 */
  public String getName() {
    return ManagementFactory.getRuntimeMXBean().getVmName();
  }

  public String getVersion() {
    return version;
  }

  public void setVersion(String version) {
    this.version = version;
  }

  public String getHome() {
    return home;
  }

  public void setHome(String home) {
    this.home = home;
  }

  /** JDK启动时间 */
  public String getStartTime() {

    return DateTimeFormatter.ofPattern(DatePattern.CHINESE_DATE_TIME_PATTERN)
        .format(getServerStartDate());
  }

  /** JDK运行时间 */
  public String getRunTime() {

    // java.time.Duration duration = java.time.Duration.between(
    // getServerStartDate(),LocalDateTime.now());
    LocalDateTime now = LocalDateTime.now();
    LocalDateTime start = getServerStartDate();
    // 获取秒数
    long nowSecond = now.toEpochSecond(ZoneOffset.ofHours(0));
    long startSecond = start.toEpochSecond(ZoneOffset.ofHours(0));
    long absSeconds = Math.abs(nowSecond - startSecond);
    // 获取秒数
    long s = absSeconds % 60;
    // 获取分钟数
    long m = absSeconds / 60 % 60;
    // 获取小时数
    long h = absSeconds / 60 / 60 % 24;
    // 获取天数
    long d = absSeconds / 60 / 60 / 24;

    return d + "天" + h + "时" + m + "分" + s + "秒";
  }

  /** 获取服务器启动时间 */
  private LocalDateTime getServerStartDate() {
    long time = ManagementFactory.getRuntimeMXBean().getStartTime();
    return LocalDateTime.ofInstant(Instant.ofEpochMilli(time), ZoneId.systemDefault());
  }
}
